//
//  CAUpgradeGoodsViewController.m
//  LNH
//
//  Created by twentylx on 2018/2/13.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAUpgradeGoodsViewController.h"
#import "CAUpgradeGoodsCollectionViewCell.h"
#import "CAUpgradeGoodsApi.h"
#import "LNHGoodsDetailViewController.h"

@interface CAUpgradeGoodsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate> {
    NSString *_goodsId;
}

@property (nonatomic, strong) UILabel *tipsLabel;

@property (nonatomic, strong) UICollectionView *goodsCollectionView;
@property (nonatomic, strong) NSArray *goodsArray;

@property (nonatomic, strong) UILabel *inviteCodeLabel;
@property (nonatomic, strong) UITextField *inviteCodeTextField;

@property (nonatomic, strong) UIButton *submitButton;

@end

@implementation CAUpgradeGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/// 初始化数据
- (void)lm_initialDefaultsForController {
    [self loadData];
}

/// 绑定 vm
- (void)lm_bindViewModelForController {
    
}

/// 创建视图
- (void)lm_createViewForController {
    [self.view setNeedsUpdateConstraints];
    
    [self.view addSubview:self.tipsLabel];
    [self.view addSubview:self.goodsCollectionView];
    [self.view addSubview:self.inviteCodeLabel];
    [self.view addSubview:self.inviteCodeTextField];
    [self.view addSubview:self.submitButton];
}

/// 配置导航栏
- (void)lm_configNavigationForController {
    self.navigationItem.title = @"选择礼包";
}

#pragma mark layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
    
    [_tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(50);
//        make.width.mas_equalTo(200);
    }];
    
    [_goodsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.tipsLabel.mas_bottom).offset(20);
        make.height.mas_equalTo(200);
    }];

    [_inviteCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(80);
        make.top.equalTo(self.goodsCollectionView.mas_bottom).offset(30);
    }];

    [_inviteCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.inviteCodeLabel.mas_right);
        make.centerY.equalTo(self.inviteCodeLabel);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(20);
    }];

    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (isIPhoneX) {
            make.bottom.equalTo(self.view).offset(-30);
        } else {
            make.bottom.equalTo(self.view);
        }
        make.height.mas_equalTo(44);
    }];
}

#pragma mark get & set
- (UILabel *)tipsLabel {
    if (!_tipsLabel) {
        _tipsLabel = [UILabel new];
        _tipsLabel.text = @"购买其中一个产品立即升级为VIP";
        _tipsLabel.font = [UIFont systemFontOfSize:18];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.numberOfLines = 2;
    }
    return _tipsLabel;
}

- (UICollectionView *)goodsCollectionView {
    if (!_goodsCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setMinimumLineSpacing:10];
        [layout setMinimumInteritemSpacing:0];
        [layout setSectionInset:(UIEdgeInsets){ 0, 20, 20, 20 }];
        [layout setItemSize:CGSizeMake((SCREEN_WIDTH-80)/3, 200)];
        
        _goodsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _goodsCollectionView.backgroundColor = [UIColor whiteColor];
        [_goodsCollectionView registerClass:[CAUpgradeGoodsCollectionViewCell class] forCellWithReuseIdentifier:@"goodsCell"];
        _goodsCollectionView.delegate = self;
        _goodsCollectionView.dataSource = self;
        
    }
    return _goodsCollectionView;
}

- (UILabel *)inviteCodeLabel {
    if (!_inviteCodeLabel) {
        _inviteCodeLabel = [UILabel new];
        _inviteCodeLabel.text = @"上级推荐码：";
        _inviteCodeLabel.font = [UIFont systemFontOfSize:14];
    }
    return _inviteCodeLabel;
}

- (UITextField *)inviteCodeTextField {
    if (!_inviteCodeTextField) {
        _inviteCodeTextField = [UITextField new];
        _inviteCodeTextField.layer.borderWidth = 1;
        _inviteCodeTextField.layer.borderColor = [RGBCOLOR(130, 130, 130) CGColor];
        _inviteCodeTextField.layer.cornerRadius = 5;
    }
    return _inviteCodeTextField;
}

- (UIButton *)submitButton {
    if (!_submitButton) {
        _submitButton = [UIButton new];
        [_submitButton setTitle:@"立即购买" forState:UIControlStateNormal];
        _submitButton.titleLabel.font = [UIFont systemFontOfSize:20];
        _submitButton.backgroundColor = RGBCOLOR(233, 85, 19);
        [_submitButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitButton;
}

#pragma mark private method
- (void) loadData {
    CAUpgradeGoodsApi *upgradeGoodsApi = [[CAUpgradeGoodsApi alloc] initWithLevelId:self.level];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [upgradeGoodsApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CAUpgradeGoodsApi *api = (CAUpgradeGoodsApi *) request;
        if (api.done) {
            _goodsArray = api.responseObject[@"result"];
            [_goodsCollectionView reloadData];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void) submitAction {
    NSString *router = [JLRoutes lm_generateURLWithPattern:LMNavPushRoute parameters:@[NSStringFromClass(LNHGoodsDetailViewController.class)] extraParameters:@{@"goodsId":_goodsId,@"level":self.level,@"inviteCode:":self.inviteCodeTextField.text,@"districtId":self.districtId}];
    [[RACScheduler mainThreadScheduler] schedule:^{
        
        [[UIApplication sharedApplication] openURL:JLRGenRouteURL(LMDefaultRouteSchema, router) options:nil completionHandler:nil];
        
    }];
}

#pragma mark UIConllectionView DataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.goodsArray.count;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CAUpgradeGoodsCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"goodsCell" forIndexPath:indexPath];
    NSDictionary *dict = self.goodsArray[indexPath.row];
    NSString *goodsId = [NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]];
    if ([goodsId isEqualToString:_goodsId]) {
        cell.selectedImageView.hidden = NO;
    } else {
        cell.selectedImageView.hidden = YES;
    }
//    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, dict[@"goods_img"]];
//    [cell.goodsImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
    cell.invitePriceLabel.text = [NSString stringWithFormat:@"推荐价：%@", dict[@"upgrade_price"]];
    cell.priceLabel.text = [NSString stringWithFormat:@"原价：%@", dict[@"price"]];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = self.goodsArray[indexPath.row];
    _goodsId = [NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]];
    [self.goodsCollectionView reloadData];
}

@end
